const invoices = require("../asset/invoices.json")
const plays = require("../asset/plays.json")


/**
 * 核心程序
 * @param {*} invoice 
 * @param {*} plays 
 * @returns 
 */
function statement(invoice, plays) {
  let result = `Statement for ${invoice.customer}\n`;
  for (let perf of invoice.performances) {
    result += ` ${playFor(perf).name}: ${usd(amountFor(perf))} (${perf.audience} seats)\n`;
  }
  result += `Amount owed is ${usd(totalAmount())}\n`;
  result += `You earned ${totalVolumeCredits() } credits\n`;
  return result;
}


/**
 * 计算总费用
 */
function totalAmount() {
  let result = 0;
  for (let perf of invoice.performances) {
    result += amountFor(perf);
  }
  return result;
}

/**
 * 计算观众量积分总和
 */
function totalVolumeCredits() {
  let result = 0;
  for (let perf of invoice.performances) {
    result += volumeCreditsFor(perf);

  }
  return result;

}


/**
 * 将数字格式化为 货币 & 将美分转换为美元（除以100）
 * @param {*} aNumber 
 */
function usd(aNumber) {
  return new Intl.NumberFormat("en-US",
    {
      style: "currency", currency: "USD",
      minimumFractionDigits: 2
    }).format(aNumber / 100);
}


/**
 * 计算观众量积分
 * @param {*} perf 
 * @returns 积分
 */
function volumeCreditsFor(aPerformance) {
  let result = 0;
  result += Math.max(aPerformance.audience - 30, 0);
  if ("comedy" === playFor(aPerformance).type) result += Math.floor(aPerformance.audience / 5);
  return result;
}


/**
 * 根据账单中的数据获取对应剧目信息
 * @param {*} aPerformance 
 * @returns 
 */
function playFor(aPerformance) {
  return plays[aPerformance.playID];
}

// 根据 perf 初始化 thisAmount 
function amountFor(aPerformance) {
  let result = 0;
  switch (playFor(aPerformance).type) {
    case "tragedy":
      result = 40000;
      if (aPerformance.audience > 30) {
        result += 1000 * (aPerformance.audience - 30);
      }
      break;
    case "comedy":
      result = 30000;
      if (aPerformance.audience > 20) {
        result += 10000 + 500 * (aPerformance.audience - 20);
      }
      result += 300 * aPerformance.audience;
      break;
    default:
      throw new Error(`unknown type: ${playFor(aPerformance).type}`);
  }
  return result;
}


// 调用
let invoice = invoices[0];
res = statement(invoice, plays);
console.log(res);
